package org

import (
	"fmt"
	"time"
	"strings"
	"errors"
	"dhfshop/models"
	"dhfshop/models/consts"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type Role struct {
	RoleId        int64      `orm:"auto;pk;column(role_id)" json:"role_id" form:"role_id"`
	PartnerId     int64      `orm:"column(partner_id);index" json:"partner_id" form:"partner_id"`
	Name          string     `orm:"column(name)" json:"name" form:"name,omitempty"`
    Menu          string     `orm:"column(menu);type(text)" json:"menu" form:"menu"`                       //菜单
	CreatedAt     time.Time  `orm:"auto_now_add;type(datetime);column(created_at)" json:"-" form:"-"`     
	UpdatedAt     time.Time  `orm:"auto_now;type(datetime);column(updated_at)" json:"-" form:"-"`         
	IsSys         bool   `orm:"column(is_sys)" json:"is_sys" form:"is_sys"`                           //系统预设角色
	IsSuperAdmin  bool   `orm:"column(is_super_admin)" json:"is_super_admin" form:"is_super_admin"`   //超级管理员
	DataRange     string `orm:"column(data_range);type(text)" json:"data_range" form:"data_range"` //数据权限: {"store_ids":[1,2],"app_ids":["1","2"]}
	IsForwardMsg  int `orm:"column(is_forward_msg);default(0)" json:"is_forward_msg" form:"is_forward_msg"` //是否转发客服消息和未读通知,1:转发
	//CustLimit   int `orm:"column(cust_limit)" json:"cust_limit" form:"cust_limit"`         //客户数上限设定,以便按需付费
	// 非数据库字段
	Permissions    []*Permission  `orm:"-" json:"permissions"`
	PermissionsStr string         `orm:"-" json:"-" form:"permissions"`
	CreatedAtStr   string         `orm:"-" json:"created_at"`
    UpdatedAtStr   string         `orm:"-" json:"updated_at"`
}

func init() {
	orm.RegisterModel(new(Role))
}

// AddRole insert a new Role into database and returns
func AddRole(m *Role) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return id, err
}

func GetAllRoles(query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*Role,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Role))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*Role
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
	    for _, role := range lists {
			role.CreatedAtStr = role.CreatedAt.Format(consts.DATETIME_FORMAT)
            role.UpdatedAtStr = role.UpdatedAt.Format(consts.DATETIME_FORMAT)
			role.Permissions, _ = GetPermissionsByRoleId(role.RoleId)
	    }
		return lists, cnt, nil
	}
	return nil, 0, err
}

func GetPartnerIdByRoleId(id int64) (v *Role, err error) {
	o := models.GetDefaultDB()
	v = &Role{RoleId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetRoleIdsByPartnerIdAndSet(partnerId int64, isForwardMsg int) (roleIds []int64, err error) {
	roles := []*Role{}
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Role)).Filter("partner_id",partnerId).Filter("is_forward_msg",isForwardMsg)
	if _, err = qs.All(&roles); err == nil {
		for _, role := range roles {
		    roleIds = append(roleIds, role.RoleId)
		}
	}
	return
}

func GetRoleByRoleId(id int64) (v *Role, err error) {
	o := models.GetDefaultDB()
	v = &Role{RoleId: id}
	if err = o.Read(v); err == nil {
		v.CreatedAtStr = v.CreatedAt.Format(consts.DATETIME_FORMAT)
        v.UpdatedAtStr = v.UpdatedAt.Format(consts.DATETIME_FORMAT)
		v.Permissions, _ = GetPermissionsByRoleId(id)
		return v, nil
	}
	return nil, err
}

func GetRoleByPartnerIdAndName(partnerId int64, name string) (v *Role, err error) {
	o := models.GetDefaultDB()
	v = &Role{PartnerId:partnerId, Name:name}
	if err = o.Read(v, "PartnerId", "Name"); err == nil {
		return v, nil
	}
	return nil, err
}

func UpdateRoleById(m *Role,param ... string) (err error) {
	o := models.GetDefaultDB()
	v := Role{RoleId: m.RoleId}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m, param...); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

func DeleteRole(id int64) (err error) {
	o := models.GetDefaultDB()
	v := Role{RoleId: id}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&v); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

func  CheckRoleExistByPartner(partnerId, roleId int64) bool {
	o := models.GetDefaultDB()
	exist := o.QueryTable(new(Role)).Filter("partner_id", partnerId).Filter("role_id", roleId).Exist()
	return exist
}

//新开店铺-初始化默认管理员角色
func InitDefaultAdminRole(partnerId int64) (int64, error) {
	role := Role{PartnerId:partnerId, Name:"超级管理员", IsSys:true, IsSuperAdmin:true, IsForwardMsg:1}
	roleId ,err := AddRole(&role)
	if err != nil {
	    return roleId, err
	}
	return roleId, nil
}

//初始化默认API角色
func InitDefaultApiRole(partnerId int64) (int64, error) {
	role := Role{PartnerId:partnerId, Name:"API访问接口", IsSys:true, IsSuperAdmin:false, IsForwardMsg:0}
	roleId ,err := AddRole(&role)
	if err != nil {
	    return roleId, err
	}
	//添加可访问API列表
	return roleId, nil
}
